package com.forte.productdao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class ProductDAOImpl implements ProductDAO {
	
	private SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory  sessionFactory){
		this.sessionFactory = sessionFactory;
	}
	
	protected final Session getCurrentSession(){
		return sessionFactory.getCurrentSession();
	}

	public void saveOrUpdate(Product product) {
		getCurrentSession().saveOrUpdate(product);
	}

	public Product findProductByProductId(int productId) {
		Query query = getCurrentSession().createQuery(
				"from products where productId = :productId");
		query.setParameter("productId", productId);
		return foundProduct(query.list());
	}
	
	@SuppressWarnings("rawtypes")
	public Product foundProduct(List list){
		Product prodFound = null;
		if(list.size() > 0){
			prodFound = (Product) list.get(0);
		}
		return prodFound;
	}

	public Product findProductByProductName(String productName) {
		Query query = getCurrentSession().createQuery(
				"from products where productName = :productName");
		query.setParameter("productName", productName);
		return foundProduct(query.list());
	}

	@SuppressWarnings("unchecked")
	public List<Product> findProductByCategoryId(int categoryId) {
		Query query = getCurrentSession().createQuery("from products where categoryId = :categoryId");
		query.setParameter("categoryId", categoryId);
		
		return (List<Product>) query.list();
	}

	public void delete(Product product) {
		getCurrentSession().delete(product);
	}

	@SuppressWarnings("unchecked")
	public List<Product> findAllProduct() {
		Query query = getCurrentSession().createQuery("from products");
		return query.list();
	}

}
